<template>
  <div class="member-list">
    <template v-if="showPage">
      <a-tabs v-model:activeKey="currentTableTab" @change="getList">
        <a-tab-pane :key="-1" :tab="tab1"></a-tab-pane>
        <a-tab-pane :key="0" :tab="tab2"></a-tab-pane>
        <template #tabBarExtraContent>
          <a-button
            type="primary"
            class="ml-20"
            style="border-radius: 6px"
            @click="inviteMemberVisible = true"
          >
            <template #icon><UserAddOutlined /></template>
            邀请成员
          </a-button>
        </template>
      </a-tabs>
      <a-table
        :dataSource="dataSource"
        :columns="columns"
        :pagination="pagination"
        @change="handleTableChange"
        rowKey="id"
        :loading="tableLoading"
      >
        <template #user="{ record }">
          <div style="display: flex; align-items: center">
            <img
              :src="record.avatar"
              alt=""
              v-if="record.avatar"
              style="
                width: 32px;
                height: 32px;
                border-radius: 4px;
                object-fit: cover;
                cursor: pointer;
              "
              @click.stop="openUrl(record.avatar)"
            />
            <span
              v-else
              style="
                width: 32px;
                height: 32px;
                border-radius: 4px;
                background-color: #f1f1f1;
                display: inline-block;
              "
            ></span>
            <span style="margin-left: 10px">{{ record.nickname || "--" }}</span>
          </div>
        </template>
        <template #phone="{ text }">
          <span>{{ text || "--" }}</span>
        </template>

        <template #action="{ record }">
          <template v-if="isAdmin">
            <template v-if="record.status == 0">
              <a-button
                type="link"
                style="padding: 0; margin: 0; color: #52c41a"
                @click.stop="editClick(record.id, 1)"
                >同意</a-button
              >
              <a-button
                type="link"
                danger
                style="padding: 0; margin-right: 0; margin-left: 10px"
                @click.stop="editClick(record.id, 4)"
                >删除</a-button
              >
            </template>
            <template v-if="record.status == 1 && !record.is_creator">
              <a-button
                type="link"
                danger
                style="padding: 0; margin-right: 0"
                @click.stop="deleteClick(record.id)"
                >移除</a-button
              >
            </template>
            <template v-else>-</template>
          </template>
          <template v-else>-</template>
        </template>
      </a-table>
    </template>

    <LoginModal
      :visible="loginVisible"
      @onClose="loginVisible = false"
      @loginCallback="loginCallback"
    />

    <InviteMember
      :visible="inviteMemberVisible"
      @onClose="inviteMemberVisible = false"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  computed,
  watch,
  toRaw,
  h,
  onBeforeUnmount,
  createVNode,
  inject,
} from "vue";
import request from "../../common/utils/request";
import store from "../../store/index";
import { useRoute, useRouter } from "vue-router";
import utils from "../../common/utils/utils";
import { Modal, notification, message } from "ant-design-vue";
import {
  UserAddOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import InviteMember from "../../components/InviteMember/index.vue";
export default defineComponent({
  name: "Create",
  components: {
    UserAddOutlined,
    InviteMember,
  },

  setup() {
    const route = useRoute();
    const router = useRouter();

    const state = reactive({
      loginVisible: false,
      showPage: false,

      page: 1,
      pageSize: 10,
      total: 0,
      dataSource: [],
      columns: [
        {
          title: "用户",
          slots: {
            customRender: "user",
          },
          width: "20%",
        },
        {
          title: "手机号码",
          dataIndex: "phone",
          slots: {
            customRender: "phone",
          },
          width: "20%",
        },
        {
          title: "加入时间",
          dataIndex: "created_at",
          slots: {
            customRender: "created_at",
          },
          width: "15%",
        },
        {
          title: "操作",
          slots: {
            customRender: "action",
          },
          width: "10%",
          align: "center",
        },
      ],

      isAdmin: false,
      tab1: "全部（0）",
      tab2: "待审批（0）",
      currentTableTab: -1,
      tableLoading: false,

      inviteMemberVisible: false,
    });

    // 操作：同意、拒绝
    const editClick = (id, status) => {
      request
        .put("/work_ai", "/user/team/user", {
          id,
          status,
        })
        .then((res) => {
          message.success("操作成功");
          state.page = 1;
          getList();
        });
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getList();
    };

    const getList = () => {
      state.tableLoading = true;
      let params = {
        page: state.page,
        pageSize: state.pageSize,
        team_id: store.state.user.teamId,
      };
      if (state.currentTableTab >= 0) {
        params.status = state.currentTableTab;
      }
      request
        .get("/work_ai", "/user/team/user/list", { ...params })
        .then((res) => {
          if (res.list && res.list.data) {
            state.dataSource = res.list.data;
          }
          state.total = res.total;
          if (res.team && res.team.can_edit) {
            state.isAdmin = true;
          } else {
            state.isAdmin = false;
          }
          if (res.count) {
            state.tab1 = `全部（${res.count.all}）`;
            state.tab2 = `待审批（${res.count.approval}）`;
          }
          state.tableLoading = false;
        });
    };

    const init = () => {
      state.page = 1;
      state.pageSize = 10;
      state.total = 0;
      if (store.state.user.teamId) {
        state.notMember = false;
        getList();
      } else {
        state.notMember = true;
      }
    };

    utils.checkLogin().then((isLogin) => {
      if (!isLogin) {
        state.loginVisible = true;
        return;
      }
      state.showPage = true;
      init();
    });

    const loginCallback = () => {
      state.loginVisible = false;
      router.go(0);
    };

    // 删除
    const deleteClick = (id) => {
      Modal.confirm({
        title: () => `确定要移除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
            .del("/work_ai", "/user/team/user", {
              id,
            })
            .then((res) => {
              message.success("删除成功");
              state.page = 1;
              getList();
            });
        },
      });
    };

    watch(
      () => store.state.user.teamId,
      (val) => {
        init();
      }
    );

    return {
      ...toRefs(state),
      loginCallback,

      pagination,
      handleTableChange,
      getList,
      editClick,
      deleteClick,
    };
  },
});
</script>

<style lang="less" scoped>
.member-list {
  width: 100%;
  height: 100%;
  padding: 20px;
}
</style>
